import { Application } from 'egg'
import { Schema } from 'mongoose'
import * as AutoIncrementFactory from 'mongoose-sequence'
/**
 * 约束模型
 */
export interface UserProps {
  username: string;
  password: string;
  email?: string;
  nickName?: string;
  picture?: string;
  phoneNumber?: string;
  createdAt: Date;
  updatedAt: Date;
  loginType:'emil'|'cellphone'|'oauth',
  oauthType?:'gitee',
  oauthId?:string
}

/**
 * 创建用户，对传入的用户信息进行验证约束
 * @param app
 * @return
 */
function initUserModel(app: Application) {
  const AutoIncrement = AutoIncrementFactory(app.mongoose)
  const UserSchema = new Schema<UserProps>({
    username: { type: String, unique: true, required: true }, // type:传入的类型；required：是否必传；unique:是否可重复
    password: { type: String },
    nickName: { type: String },
    picture: { type: String },
    email: { type: String },
    phoneNumber: { type: String },
    loginType: { type: String, default: 'email' },
    oauthType: { type: String, default: 'gitee' },
    oauthId: { type: String, },
  }, { timestamps: true,
    toJSON: {
      transform(_doc, ret) {
        delete ret.password;
        delete ret.__v
      }
    } })// 自动为createdAt，updatedAt赋值
  UserSchema.plugin(AutoIncrement, { inc_field: 'id', id: 'user_id_counter' })
  return app.mongoose.model<UserProps>('User', UserSchema)
}

export default initUserModel
